﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace Twi.COMMON.Core
{
    /*
    * Copyright: ©2010-2011 Twilight软件开发工作室版权所有
     * Create By:xuzhihong
     * Create Date: 2010-11-22
     * Description:  将IEnumerable<T>转换为DataTable
     * 两个方法效果一样
     */


    public class LinqToDataTable
    {
        /// <summary>
        /// 不支持 System.Nullable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static DataTable GetTable<T>(IEnumerable<T> data)
        {
            var dt = new DataTable();
            var ps = typeof(T).GetProperties().ToList();
            ps.ForEach(p => dt.Columns.Add(p.Name, p.PropertyType));
            foreach (T t in data)
            {
                var dr = dt.NewRow();
                var vs = from p in ps
                         select p.GetValue(t, null);
                var ls = vs.ToList();
                int i = 0;
                ls.ForEach(c => dr[i++] = c);
                dt.Rows.Add(dr);
            }
            return dt;
        }

        /// <summary> 
        /// 微软提供的方法
        /// </summary> 
        /// <typeparam name="T"> </typeparam> 
        /// <param name="varlist"> </param> 
        /// <returns> </returns> 
        public static DataTable ToDataTable<T>(IEnumerable<T> varlist)
        {
            DataTable dtReturn = new DataTable();

            // column names 
            PropertyInfo[] oProps = null;

            if (varlist == null)
                return dtReturn;

            foreach (T rec in varlist)
            {
                if (oProps == null)
                {
                    oProps = ((Type)rec.GetType()).GetProperties();
                    foreach (PropertyInfo pi in oProps)
                    {
                        Type colType = pi.PropertyType;

                        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
                        == typeof(Nullable<>)))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }

                        dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                    }
                }

                DataRow dr = dtReturn.NewRow();

                foreach (PropertyInfo pi in oProps)
                {
                    dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                    (rec, null);
                }

                dtReturn.Rows.Add(dr);
            }
            return dtReturn;
        } 
    }
}
